package org.jdk.learning.thread;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author xin
 * @version 1.0
 */
public class CyclicBarrierDemo {

    public static void main(String[] args) {
        int count = 3;
        //创建包含3个线程的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(count);
        //创建barrier
        CyclicBarrier barrier = new CyclicBarrier(count, () -> System.out.println("-------------------------"));
        //将任务提交给线程池
        IntStream.range(0, count).forEach(i -> executorService.submit(new Runner("选手" + (i + 1), barrier, count)));
        //关闭线程池
        executorService.shutdown();
    }


}

class Runner implements Runnable {

    private CyclicBarrier barrier;

    private String name;

    private int cycleCount;

    Runner(String name, CyclicBarrier barrier, int cycleCount) {
        this.name = name;
        this.barrier = barrier;
        this.cycleCount = cycleCount;
    }

    @Override
    public void run() {
        Random random = new Random();
        IntStream.range(0, cycleCount).forEach(i -> {
            try {
                //当await()调用次数和创建barrier时传入的count相同时，所有调用await()的线程都会唤醒
                barrier.await();
                TimeUnit.SECONDS.sleep(random.nextInt(5));
                System.out.println(name + "跑完第" + (i + 1) + "圈");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        });

    }
}
